package ua.kpi_java_training.zabrodskyi.module2;

/**
 * @author Maksym Zabrodskyi
 * @version 10-Jun-2013
 */
public class Life {

    private int lengthLife;

    public Life(int lengthLife) {
        if (lengthLife <= 0) {
            throw new RuntimeException(
                    "Error: incorrect value of length of life.");
        }
        this.lengthLife = lengthLife;
    }

    public void run(Pool pool) {
        for (int time = 1; time <= lengthLife; time++) {
            printThisCycle(time);
            doOneCycle(pool);
        }
    }

    private void printThisCycle(int time) {
        String dash = String.format("%0" + 15 + "d", 0).replace("0", "= ");
        Printer.printToConsole(dash + "Life cycle = ", time);
    }

    private void doOneCycle(Pool pool) {
        for (int index = 0; index < pool.getSize(); index++) {
            if (new Fish().equals(pool.getObject(index))) {
                Fish fish = (Fish) pool.getObject(index);
                fish.move(pool);
                fish.eat(pool);
                fish.spawn(pool);
                Printer.printToConsole(fish.toString());
            }
        }
    }

    @Override
    public String toString() {
        return String.format("Life goes %s times", lengthLife);
    }

}
